package com.las.bot.cmd.jisu;

import com.alibaba.fastjson.JSONObject;
import com.utils.JsonUtils;
import com.las.annotation.BotCmd;
import com.las.cmd.BaseCommand;
import com.las.utils.HttpUtils;
import com.las.utils.mirai.CmdUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;

@BotCmd(funName = "汇率转换")
public class ExchangeCmd extends BaseCommand {

    private String[] currency = {"HKD", "JPY", "USD", "EUR", "AUD", "DKK", "GBP", "IDR", "KRW", "TWD"
            , "RUB", "PHP", "SEK", "SGD", "THB", "IRR", "MOP"};

    public ExchangeCmd() {
        super("汇率", "HKD", "JPY", "USD", "EUR", "AUD", "DKK", "GBP", "IDR", "KRW", "TWD"
                , "RUB", "PHP", "SEK", "SGD", "THB", "IRR", "MOP");
    }

    @Override
    public void execute(Long userId, Long id, Integer type, String command, ArrayList<String> args) {
        String upCmd = command.toUpperCase();
        if (upCmd.startsWith("汇率")) {
            String cStr = Arrays.toString(currency);
            CmdUtil.sendMessage("目前支持的币种有：" + cStr + "\n\n输入指令：#USD 10 就会计算10美元转换多少人民币", userId, id, type);
        } else {
            String to = "CNY";
            String from = upCmd.substring(0, 3);
            if (args.size() > 0) {
                String number = args.get(0);
                double num = -1;
                try {
                    num = Double.parseDouble(number);
                } catch (NumberFormatException ignored) {

                }
                if(num > 0){
                    String api = "https://api.jisuapi.com/exchange/convert?appkey=09ba2644e1e957c8&from=" + from + "&to=" + to + "&amount=" + num;
                    String json = HttpUtils.doGet(api);
                    JSONObject obj = JsonUtils.getJsonObjectByJsonString(json);
                    if (0 == obj.getInteger("status")) {
                        JSONObject result = obj.getJSONObject("result");
                        Double camount = result.getDouble("camount");
                        BigDecimal finalValue = new BigDecimal(camount).setScale(4, BigDecimal.ROUND_CEILING);
                        String info = num + result.getString("fromname") + " ≈ " + finalValue + result.getString("toname");
                        String rate = result.getString("rate");
                        String dateInfo = "仅供参考，交易时以银行柜台成交价为准\n更新时间:" + result.getString("updatetime");
                        CmdUtil.sendMessage(info + "\n" + "汇率：" + rate + "\n\n" + dateInfo, userId, id, type);
                    } else {
                        CmdUtil.sendMessage("汇率API欠费了，呼叫管理员续费...", userId, id, type);
                    }
                    return;
                }
            }
            CmdUtil.sendMessage("参数错误，请重试", userId, id, type);
        }
    }
}
